package com.js.lib_common.base;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.js.lib_common.R;
import com.js.lib_common.view.DialogHelper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportFragment;


/**
 * 懒加载
 */
public abstract class BaseMainFragment extends SupportFragment {
    protected Unbinder unbinder;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    // 再点一次退出程序时间设置
    private static final long WAIT_TIME = 2000L;
    private long TOUCH_TIME = 0;


    /**
     * 处理回退事件
     *
     * @return
     */
    @Override
    public boolean onBackPressedSupport() {
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
            _mActivity.finish();
        } else {
            TOUCH_TIME = System.currentTimeMillis();
            Toast.makeText(_mActivity, R.string.press_again_exit, Toast.LENGTH_SHORT).show();
        }
        return true;
    }
    public void toastShow(int resId) {
        Toast.makeText(_mActivity, resId, Toast.LENGTH_SHORT).show();
    }

    public void toastShow(String resId) {
        Toast.makeText(_mActivity, resId, Toast.LENGTH_SHORT).show();
    }

    public Dialog loadingDialog;

    public Dialog showLoadingDialog() {
        if (loadingDialog==null)
            loadingDialog = new DialogHelper().getLoading(_mActivity, "加载中");
        if (!loadingDialog.isShowing())
            loadingDialog.show();
        return loadingDialog;
    }


    public Dialog showLoadingDialog(String message) {
        if (loadingDialog==null)
            loadingDialog = new DialogHelper().getLoading(_mActivity, message);
        if (!loadingDialog.isShowing())
            loadingDialog.show();
        return loadingDialog;
    }


    public void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            // progressDialog.hide();会导致android.view.WindowLeaked
            loadingDialog.dismiss();
        }
    }
}
